﻿/*
*类名：Qrcode
*归属：QinMing.Tools.Qrcode命名空间
*用途：根据网址生成二维码
*作者：乱世刀疤
*日期：2022.05.06
*/

using System;
using System.Web;
using System.IO;
using System.Text;
using System.Drawing;
using ThoughtWorks.QRCode.Codec;
//using QinMing.Tools;

namespace QinMing.Tools.Qrcode
{
    public  class QrcodeTools : System.Web.UI.Page
    {
		#region 生成二维码
		/// <summary>
        /// 根据网址生成二维码，并返回图片网址链接
        /// </summary>
		/// <param name="Url">需转为二维码的网址</param>
		/// <param name="SavePath">保存在web服务器根目录中的目录</param>
		/// <param name="WebServerUrl">web服务器网址</param>
		public static string GetQrcodeByUrl(string Url, string SavePath, string WebServerUrl)
		{
            System.Drawing.Bitmap bt;
 
            QRCodeEncoder qrCodeEncoder = new QRCodeEncoder();
            qrCodeEncoder.QRCodeEncodeMode = QRCodeEncoder.ENCODE_MODE.BYTE;    //编码方式(注意：BYTE能支持中文，ALPHA_NUMERIC扫描出来的都是数字)
            qrCodeEncoder.QRCodeScale = 6;    //大小(值越大生成的二维码图片像素越高)
            qrCodeEncoder.QRCodeVersion = 0;    //版本(注意：设置为0主要是防止编码的字符串太长时发生错误)
            qrCodeEncoder.QRCodeErrorCorrect = QRCodeEncoder.ERROR_CORRECTION.M;    //错误效验、错误更正(有4个等级)
            qrCodeEncoder.QRCodeBackgroundColor = Color.White;    //背景色
            qrCodeEncoder.QRCodeForegroundColor = Color.Black;     //前景色
 
            bt = qrCodeEncoder.Encode(Url, Encoding.UTF8);
 
            string path = HttpContext.Current.Request.PhysicalApplicationPath + SavePath;
            if(!Directory.Exists(path))  //获取网站根目录，加上传入的保存路径形成新目录，如果目录不存在就创建
            {
                Directory.CreateDirectory(path);
            }
			
			string filename = DateTime.Now.ToString("yyyyMMddHHmmssfff") + ".jpg";
			
			//QinMingTools.WriteLog("保存文件路径：", path + "\\" + filename);
			try
			{
				//System.IO.FileStream fs = new System.IO.FileStream(path + "\\" + filename, System.IO.FileMode.OpenOrCreate, System.IO.FileAccess.Write);
				//fs.Close();
				bt.Save(path + "\\" + filename, System.Drawing.Imaging.ImageFormat.Jpeg);    //保存图片
				bt.Dispose();				
			}
			catch(Exception exception)
			{
				//QinMingTools.WriteLog("保存文件报错：", exception.ToString());
			}
			
			//QinMingTools.WriteLog("返回图片网址：", WebServerUrl + "/" + SavePath + "/" + filename);
            return WebServerUrl + "/" + SavePath + "/" + filename;
		}
		#endregion
		
		#region 生成二维码
		/// <summary>
        /// 根据网址生成二维码，并返回图片本机路径
        /// </summary>
		/// <param name="Url">需转为二维码的网址</param>
		/// <param name="SavePath">保存在web服务器根目录中的目录</param>
		public static string GetQrcodeByUrl(string Url, string SavePath)
		{
            System.Drawing.Bitmap bt;
 
            QRCodeEncoder qrCodeEncoder = new QRCodeEncoder();
            qrCodeEncoder.QRCodeEncodeMode = QRCodeEncoder.ENCODE_MODE.BYTE;    //编码方式(注意：BYTE能支持中文，ALPHA_NUMERIC扫描出来的都是数字)
            qrCodeEncoder.QRCodeScale = 6;    //大小(值越大生成的二维码图片像素越高)
            qrCodeEncoder.QRCodeVersion = 0;    //版本(注意：设置为0主要是防止编码的字符串太长时发生错误)
            qrCodeEncoder.QRCodeErrorCorrect = QRCodeEncoder.ERROR_CORRECTION.M;    //错误效验、错误更正(有4个等级)
            qrCodeEncoder.QRCodeBackgroundColor = Color.White;    //背景色
            qrCodeEncoder.QRCodeForegroundColor = Color.Black;     //前景色
 
            bt = qrCodeEncoder.Encode(Url, Encoding.UTF8);
 
            string path = HttpContext.Current.Request.PhysicalApplicationPath + SavePath;
            if(!Directory.Exists(path))  //获取网站根目录，加上传入的保存路径形成新目录，如果目录不存在就创建
            {
                Directory.CreateDirectory(path);
            }
			
			string filename = DateTime.Now.ToString("yyyyMMddHHmmssfff") + ".jpg";
			
			//QinMingTools.WriteLog("保存文件路径：", path + "\\" + filename);
			try
			{
				//System.IO.FileStream fs = new System.IO.FileStream(path + "\\" + filename, System.IO.FileMode.OpenOrCreate, System.IO.FileAccess.Write);
				//fs.Close();
				bt.Save(path + "\\" + filename, System.Drawing.Imaging.ImageFormat.Jpeg);    //保存图片
				bt.Dispose();				
			}
			catch(Exception exception)
			{
				//QinMingTools.WriteLog("保存文件报错：", exception.ToString());
			}
			
			//QinMingTools.WriteLog("返回图片路径：", WebServerUrl + "/" + SavePath + "/" + filename);
            return path + "\\" + filename;
		}
		#endregion
		
		#region 生成二维码
		/// <summary>
        /// 将二维码转换成网页可以显示的数据
        /// </summary>
		/// <param name="Url">需转为二维码的网址</param>
		public static string GetQrcodeImageData(string Url)
		{

            QRCodeEncoder qrCodeEncoder = new QRCodeEncoder();
            qrCodeEncoder.QRCodeEncodeMode = QRCodeEncoder.ENCODE_MODE.BYTE;
            qrCodeEncoder.QRCodeScale = 12;
            qrCodeEncoder.QRCodeVersion = 0;
            qrCodeEncoder.QRCodeErrorCorrect = QRCodeEncoder.ERROR_CORRECTION.L;
      
            var bmp = qrCodeEncoder.Encode(Url);
 
            byte[] b = null;
            using (MemoryStream stream = new MemoryStream())
            {
                bmp.Save(stream, System.Drawing.Imaging.ImageFormat.Jpeg);//将图像以指定的格式存入缓存内存流
                b = new byte[stream.Length];
                stream.Position = 0;
                stream.Read(b, 0, Convert.ToInt32(b.Length));
            }
            return "data:image/jpeg;base64," + Convert.ToBase64String(b);

		}
		#endregion
	}
}


